package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.entity.Collect;
import com.example.entity.Product;
import com.example.entity.User;
import com.example.mapper.CollectMapper;
import com.example.mapper.ProductMapper;
import com.example.service.ICollectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.service.IUserService;
import com.example.utils.Result;
import com.example.vo.CollectVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cyz
 * @since 2022-06-19
 */
@Service
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements ICollectService {

    @Autowired
    private IUserService userService;

    @Autowired
    private CollectMapper collectMapper;

    @Autowired
    private ICollectService collectService;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Result saveCollect(String token, Integer productId) {
        User check = userService.check(token);

        LambdaQueryWrapper<Collect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Collect::getProductId,productId);
        queryWrapper.eq(Collect::getUserId,check.getId());
        Collect selectOne = collectMapper.selectOne(queryWrapper);
        if (selectOne!=null){
            return Result.fail(400,"商品已经收藏,不能添加");
        }
        Collect collect = new Collect();
        collect.setUserId(check.getId());
        collect.setProductId(productId);
        boolean save = collectService.save(collect);
        if (save){
            return Result.success("添加收藏成功");
        }else {
            return Result.fail(400,"添加收藏失败");
        }
    }

    @Override
    public Result getListByUser(Integer userId) {
        LambdaQueryWrapper<Collect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Collect::getUserId,userId);
        List<Collect> collects = collectMapper.selectList(queryWrapper);
        ArrayList<CollectVo> CollectVoList = new ArrayList<>();
        for (Collect collect : collects) {
            Product product = productMapper.selectById(collect.getProductId());
            CollectVo collectVo = new CollectVo();
            BeanUtils.copyProperties(product,collectVo);
            BeanUtils.copyProperties(collect,collectVo);
            CollectVoList.add(collectVo);
        }
        return Result.success(CollectVoList);
    }
}
